<?php
include_once 'fun.php';
$add = [];
$add['unit'] = function ($cmd, $token) {
  if ($token['type'] == 管理员) {
    $cmd = [
      'table' => 'unit',
      'name' => $cmd['name'],
      'other' => json_encode($cmd['other'], JSON_UNESCAPED_UNICODE)
    ];
  } else return noPrem;
  $ret = AddData($cmd);
  return ['result' => $ret];
};
$add['itemType'] = function ($cmd, $token) {
  if ($token['type'] == 管理员) {
    $cmd = [
      'table' => 'itemType',
      'pid' => (int) $cmd['pid'],
      'name' => $cmd['name'],
      'other' => $cmd['other']
    ];
  } else return noPrem;
  $ret = AddData($cmd);
  return ['result' => $ret];
};
$add['depository'] = function ($cmd, $token) {
  if ($token['type'] == 管理员) {
    $cmd = [
      'table' => 'depository',
      'pid' => $cmd['pid'],
      'userType' => $cmd['userType'],
      'name' => $cmd['name'],
      'other' => $cmd['other']
    ];
  } else return noPrem;
  $ret = AddData($cmd);
  return ['result' => $ret];
};

function GetItemTypeByName($name, $pid = 0)
{
  $ret = GetData(['table' => strtolower('itemType'), 'pid' => $pid, 'name' => $name]);
  if ($ret['error']) {
    $ret = AddData(['table' => strtolower('itemType'), 'pid' => $pid, 'name' => $name, 'other' => '{"remarks":"批量导入"}']);
    if ($ret['error']) $ret = [];
  } else $ret = $ret[0];
  return $ret;
};
$add['items'] = function ($cmd, $token) {
  if ($token['type'] == 管理员 || $token['type'] == 信息员) {
    $sql = [];
    if (isset($cmd['items'])) {
      $ret = ['items' => [], 'itemType' => GetData(['table' => strtolower('itemType')])];
      if ($ret['itemType']['error']) $ret['itemType'] = [];
      // runSql('TRUNCATE ' . strtolower('itemType'));
      // runSql('TRUNCATE items');
      foreach ($cmd['items'] as $k => $v) {
        $t = explode(',', $v['pid']);
        foreach ($t as $key => $name) { // 创建itemType
          $pid = 0;
          if ($key) {
            $pid = $t[$key - 1];
          }
          $tmp = getItem($ret['itemType'], ['name' => $name, 'pid' => $pid]);
          // $cf[] = $tmp;
          // return [$t, ['name' => $name, 'pid' => $pid], !$tmp];
          // if ($k) return [$tmp, ['name' => $name, 'pid' => $pid], !$tmp];
          if (!$tmp) {
            if ($token['type'] == 信息员) {
              $k += 2;
              return ['error' => "第$k 行数据处出现错误.信息员无新建分类权限."];
            }
            $tmp = AddData([
              'table' => strtolower('itemType'),
              'pid' => $pid,
              'name' => $name,
              'other' => '{"remarks":"批量导入"}'
            ]);
            $ret['itemType'][] = $tmp;
          }
          // else {
          //   $cf[] = $tmp;
          // }
          $t[$key] = $tmp['id'];
        }
        $item = [
          'table' => 'items',
          'pid' =>  $t[count($t) - 1],
          'uid' => $v['uid'],
          'name' => $v['name'],
          'model' => $v['model'],
        ];
        $i = GetData($item);
        if ($i['error']) {
          $ret['items'][] = AddData(array_merge($item, [
            'cid' => 0,
            'units' => '[]',
            'sum' => 0,
            'state' => 1,
            'other' => '{"remarks":"批量导入"}'
          ]));
        } else {
          return ['error' => "第" . ($k + 2) . " 行数据处物料已存在."];
        }
      }
    } else {
      if ((int) $cmd['pid'] < 1) return ['error' => '数据错误.请填写完整'];
      $item = [
        'table' => 'items',
        'pid' => (int) $cmd['pid'],
        'uid' => $cmd['uid'],
        'name' => $cmd['name'],
        'model' => $cmd['model'],
      ];
      $sql = GetData($item);
      if ($sql['error']) {
        $ret = AddData(array_merge($item, [
          'cid' => 0,
          'units' => '[]',
          'sum' => 0,
          'state' => 1,
          'other' => $cmd['other']
        ]));
      } else {
        $ret = ['error' => '该物料已存在'];
      }
    }
  } else return noPrem;
  if ($ret['error']) return $ret;
  return ['result' => $ret];
};
$add['itemIO'] = function ($cmd, $token) {
  $cmd['type'] = (int) $cmd['type'];
  if ($cmd['type'] < 1 || $cmd['type'] > 3 || !sureArray($cmd['items'])) return ['msg' => '数据格式错误1', 'data' => $cmd];
  if ($cmd['type'] == 3 && $token['type'] != 管理员 && $token['type'] != 信息员) {
    return noPrem;
  }
  $t = ['depository', 'project', 'sum', 'process'];
  foreach ($cmd['items'] as $k => $v) { // 校验数据格式
    if (!CheckKey($v, $t)) return ['msg' => '数据格式错误2', 'data' => $cmd];
    if (!is_numeric($v['depository'])) $v['depository'] = getDepositoryByName($v['depository']);
    if (!is_numeric($v['project'])) {
      if (!isset($v['projectName'])) return ['msg' => '数据格式错误3', 'data' => $cmd];
      $pid = getProjectByName($v['projectName']);
      $v['project'] = getProjectByName($v['project'], $pid);
    }
    if (!is_numeric($v['process'])) $v['process'] = getProcessByName($v['depository']);
    if (!$v['id']) {
      if (isset($v['uid']) && isset($v['name']) && isset($v['model'])) {
        $v['id'] = getItemByName($v['uid'], $v['name'], $v['model']);
      } else return ['msg' => '数据格式错误4', 'data' => $cmd];
    }
    $cmd['items'][$k] = $v;
  }
  foreach ($cmd['items'] as $v) {
    $t = getStock($v['depository'], $v['project'], $v['id'], $v['process'], true);
    $t = [
      'table' => 'stock',
      'stock' => '=stock' . ($v['sum'] < 0 ? '-' : '+') . abs($v['sum']),
      'where' => ['id' => $t]
    ];
    if ($v['sum'] < 0) $t['`use`'] = '=`use`+' . abs($v['sum']);
    else $t['arrived'] = '=arrived+' . $v['sum'];
    UpData($t, false, true);
  }
  $ret = AddData([
    'table' => 'itemio',
    'CreateTime' => time(),
    'type' => $cmd['type'],
    'user' => $token['id'],
    'state' => 1,
    'info' => $cmd['items'],
    'other' => $cmd['other']
  ]);
  if ($ret['id']) {
    $ret = ['result' => getGlobal4(0, $token)];
  }
  return $ret;
};
$add['userType'] = function ($cmd, $token) {
  if ($token['type'] == 管理员) {
    $cmd['sum'] = 0;
    $cmd = [
      'table' => strtolower('userType'),
      'cid' => (int) $cmd['cid'],
      'pid' => $cmd['pid'],
      'name' => $cmd['name'],
      'other' => $cmd['other']
    ];
  } else return noPrem;
  $ret = AddData($cmd);
  return ['result' => $ret];
};
$add['users'] = function ($cmd, $token) {
  if ($token['type'] != 管理员) return noPrem;
  $ret = GetData(['table' => 'users', 'username' => $cmd['username']], 'id');
  if (!$ret['error']) return ['msg' => '用户名已存在!', 'data' => $cmd];
  $cmd = [
    'table' => strtolower('users'),
    'userType' => isset($cmd['userType']) ? $cmd['userType'] : 0,
    'CreateTime' => time(),
    'ChangeTime' => 0,
    'UseTime' => 0,
    'state' => isset($cmd['state']) ? $cmd['state'] : 1,
    'type' => isset($cmd['type']) ? $cmd['type'] : 巡查员,
    'username' => $cmd['username'],
    'password' => $cmd['password'],
    'name' => $cmd['name'],
    'tel' => $cmd['tel'],
    'other' => json_encode($cmd['other'], JSON_UNESCAPED_UNICODE)
  ];
  $ret = AddData($cmd);
  if (is_string($ret['other'])) $ret['other'] = json_decode($ret['other'], true);
  return ['result' => $ret];
};
$add['process'] = function ($cmd, $token) {
  if ($token['type'] == 管理员) {
    $cmd['sum'] = 0;
    $cmd = [
      'table' => strtolower('process'),
      'name' => $cmd['name'],
      'other' => json_encode($cmd['other'], JSON_UNESCAPED_UNICODE),
      'state' => (int) $cmd['state'] ? $cmd['state'] : 1,
    ];
  } else return noPrem;
  $ret = AddData($cmd);
  if (is_string($ret['other'])) $ret['other'] = json_decode($ret['other'], true);
  return ['result' => $ret];
};

$add['project'] = function ($cmd, $token) {
  $ret = '错误';
  if (
    $token['type'] == 管理员 ||
    $token['type'] == 信息员
  ) {
    if (sureArray($cmd['info'])) {
      foreach ($cmd['info'] as $v) {
        if (!in_array($v['userType'], $token['uts'])) return noPrem;
        if (sureArray($v['info'])) {
          foreach ($v['info'] as $p) {
            if (!in_array($p['userType'], $token['uts'])) return noPrem;
          }
        } else return ['error' => '权限判定_数据格式错误1!'];
      }
      $qqq = [];
      $stock = GetData(['table' => 'stock']);
      if ($stock['error']) $stock = [];
      foreach ($cmd['info'] as $v) {
        if (!(int) $v['userType']) $v['userType'] = $token['userType'];
        // return $v;
        if ($v['id']) {
          $t = GetData(['table' => 'project', 'id' => (int) $v['id']], 'id', true);
          if (isset($t['error'])) $t = 0;
        } elseif ($v['name']) {
          $t = getProjectByName($v['name'], 0, (int) $v['userType']);
        } else return ['error' => '数据格式错误1!'];
        if (!$t) return ['error' => '服务器错误1!'];
        $pid = $t;
        foreach ($v['info'] as $p) {
          if (!(int) $p['userType']) $p['userType'] = $token['userType'];
          if ($p['id']) {
            $t = GetData(['table' => 'project', 'id' => (int) $p['id']], 'id', true);
            if (isset($t['error'])) $t = 0;
          } elseif ($p['name']) {
            $t = getProjectByName($p['name'], $pid, (int) $p['userType']);
          } else return ['error' => '数据格式错误2!'];
          if (!$t) return ['error' => '服务器错误2!'];
          $project = $t;
          foreach ($p['items'] as $i) {
            if ($i['id']) {
              $t = GetData(['table' => 'items', 'id' => (int) $i['id']], 'id', true);
              if (isset($t['error'])) $t = 0;
            } elseif ($i['name']) {
              $item = GetData(['table' => 'items', 'uid' => $i['uid'], 'name' => $i['name'], 'model' => $i['model'] ? $i['model'] : '',], 'id,name');
              if ($item['error']) {
                $item = AddData([
                  'table' => 'items',
                  'cid' => 0,
                  'pid' => 1,
                  'uid' => $i['uid'],
                  'name' => $i['name'],
                  'model' => $i['model'] ? $i['model'] : '',
                  'units' => '[]',
                  'sum' => 0,
                  'state' => 1,
                  'other' => '{"remarks":"批量添加"}'
                ]);
                $item = $item['id'];
              } else {
                // $qqq[] = $item;
                $item = $item[0]['id'];
              }
            } else return ['error' => '数据格式错误3!'];
            // item=$item;
            if (!$item) return ['error' => '服务器错误3!'];
            $tmp = [
              'table' => 'stock',
              'depository' => 0,
              'project' => $project,
              'item' => $item,
              'process' => is_numeric($i['process']) ? $i['process'] : getProcessByName($i['process']),
              'sum' => (float) $i['sum'],
              'arrived' => 0,
              '`use`' => 0,
              'stock' => 0,
              'state' => 0
            ];
            $t = getItem($stock, [
              'project' => $tmp['project'],
              'item' => $tmp['item'],
              'process' => $tmp['process'],
            ], 0);
            if ($t < 0) {
              $t = AddData($tmp);
              $stock[] = $t;
            }
          }
        }
      }
      // return $stock;
      $ret = ['result' => getGlobal4(0, $token)];
      // $ret = $qqq;
    } else $ret = ['error' => '数据格式错误0!'];
  } else $ret = noPrem;
  return $ret;
};
/*
TRUNCATE TABLE `project`;
TRUNCATE TABLE `stock`
*/
